#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include <arpa/inet.h>
#include "wrap.h"


int main(){
    struct sockaddr_in server_sockaddr,client_sockaddr;
    int s_fd = Socket(AF_INET, SOCK_STREAM, 0);

    //以sockaddt_in结构体填充socket信息
    server_sockaddr.sin_family = AF_INET;//IPv4
    server_sockaddr.sin_port = htons(7777);//端口
    server_sockaddr.sin_addr.s_addr = INADDR_ANY;//本主机的任意IP都可以使用
    bzero(&(server_sockaddr.sin_zero),8);//填充0


    Bind(s_fd,(struct sockaddr *)&server_sockaddr,sizeof(struct sockaddr));

    printf("bind success!\n");

    //请求队列中允许的最大请求数量设置为5
    Listen(s_fd,5);
    printf("listen success!\n");

    socklen_t len = sizeof(client_sockaddr);
    int client_fd = Accept(s_fd, (struct sockaddr *)&client_sockaddr, &len);

    printf("accept success!\n");
    char client_ip[1024];
    printf("client ip :%s port %d\n",inet_ntop(AF_INET,&client_sockaddr.sin_addr.s_addr,client_ip,sizeof(client_ip)),ntohs(client_sockaddr.sin_port));

    char buf[1024];
    while (1){
        int ret = Readn(client_fd,buf,sizeof(buf));
        Writen(STDOUT_FILENO,buf,ret);
        int i = 0;
        for(;i<ret;i++){
            buf[i] = toupper(buf[i]);
        }
        Writen(client_fd,buf,ret);
    }
    Close(client_fd);
    Close(s_fd);
    return 0;
}